//
//  UserAccountViewModel.swift
//  AAWeibo
//
//  Created by 上官风雨 on 15/11/11.
//  Copyright © 2015年 上官风雨. All rights reserved.
//

import UIKit
import AFNetworking
//加载用户令牌
class UserAccountViewModel: NSObject {
    
    var account :UserAccount?
    
    //用户是否登录
    var userLogin :Bool {
        return account?.access_token != nil
        
    }
    
    //用户的昵称
    var userName :String? {
        
        return account?.name
    }
    
    //用户头像的url
    
    var imageUrl :NSURL? {
        
        return NSURL(string: account?.avatar_large ?? "")
        
    }
    
     override init() {
        
        account = UserAccount.loadAccount()
    }

    func loadAccess_token(code:String,finished:(error:NSError?)->()){
        
        let urlString = "https://api.weibo.com/oauth2/access_token?"
        
        let parameters = ["client_id":client_id,"client_secret":client_secret,"grant_type":"authorization_code","code":code,"redirect_uri":redirect_uri]
        let AFN = AFHTTPSessionManager()
        AFN.responseSerializer.acceptableContentTypes?.insert("text/plain")
        
        AFN.POST(urlString, parameters: parameters, success: { (_, result) -> Void in
            if let dict = result as? [String :AnyObject] {
                
     
                
                let account = UserAccount(dict: dict)
                self.loadUserInfo(account, finished: finished)
            }
            
            }) { (_, error) -> Void in
                
            print(error)
                
        }
        
    }
    
    func loadUserInfo(account:UserAccount,finished:(error:NSError?)->()){
        
        let urlString = "https://api.weibo.com/2/users/show.json"
        let parameters = ["access_token":account.access_token!,"uid":account.uid!]
        
        let AFN = AFHTTPSessionManager()
        AFN.GET(urlString, parameters: parameters, success: { (_, result) -> Void in
            
            if let dict = result as? [String:AnyObject]{
                
                account.avatar_large = dict["avatar_large"] as? String
                account.name = dict["name"] as? String
                
                account.saveAccount()
                
                finished(error: nil)
                
            }
            
            
            }) { (_, error) -> Void in
                
                finished(error: error)
        }
    }
    
}
